package com.glorystone.ins.task;

import com.glorystone.ins.domain.CreditTotal;
import com.glorystone.ins.service.ChannelService;
import com.glorystone.ins.service.CreditTotalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 渠道授信到期，修改渠道授信状态为已失效
 * <p>
 * Created by wangwei on 2018/3/28.
 */
@Slf4j
@Component
@Lazy(value = false)
public class ChannelTask {

    @Autowired
    private ChannelService channelService;
    @Autowired
    private CreditTotalService creditTotalService;


    @Scheduled(cron = "0 0 1 * * ?")
    public void applyCredit() {
        log.info("<--开始  执行授信到期校验-->");

        List<CreditTotal> list = creditTotalService.findActiveList();

        List<Long> ids = list.stream().filter(i -> i.getEndDate() != null && i.getEndDate().isBefore(LocalDate.now())).map(CreditTotal::getChannelId).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        log.debug("<--授信到期的渠道-->{}", ids);

        // 把每个渠道状态改为授信过期
        channelService.updateToCreditOverdue(ids);

        // 把授信改为已失效
        creditTotalService.updateOffByChannelIds(ids);
        log.info("<--结束  执行授信到期校验-->");

    }
}
